package net.chenlin.dp.modules.business.service.impl;

import com.google.common.base.Joiner;
import net.chenlin.dp.common.entity.Page;
import net.chenlin.dp.common.entity.Query;
import net.chenlin.dp.common.entity.R;
import net.chenlin.dp.common.utils.CommonUtils;
import net.chenlin.dp.modules.business.dao.DeviceRegisterMapper;
import net.chenlin.dp.modules.business.dao.TestManageMapper;
import net.chenlin.dp.modules.business.entity.dto.DeviceDto;
import net.chenlin.dp.modules.business.entity.dto.TestDto;
import net.chenlin.dp.modules.business.entity.po.DevicePo;
import net.chenlin.dp.modules.business.entity.po.TestPo;
import net.chenlin.dp.modules.business.entity.vo.testManage.AppTestListVo;
import net.chenlin.dp.modules.business.entity.vo.testManage.TestManageVo;
import net.chenlin.dp.modules.business.service.TestManageService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author Yangsm
 * @ClassName: TestManageServiceImpl
 * @Description: TODO
 * @date 2022年10月18日 10:40
 */
@Service
public class TestManageServiceImpl implements TestManageService {

    @Autowired
    private TestManageMapper testManageMapper;

    @Autowired
    private DeviceRegisterMapper deviceRegisterMapper;

    @Override
    public Page<TestManageVo> getUnderwayTestList(Map<String, Object> params) {
        Query query = new Query(params);
        Page<TestManageVo> page = new Page<>(query);
        List<TestManageVo> list =  testManageMapper.getUnderwayTestList(page, query);
        list.stream().forEach(testManageVo -> {
            if(testManageVo.getStatus().equals(0)){
                testManageVo.setStatusValue("进行中");
            }
        });
        return page;
    }

    @Override
    @Transactional
    public R stopTest(Long id) {
        testManageMapper.stopTest(id);
        return R.ok("终止实验操作成功");
    }

    @Override
    @Transactional
    public R creatTest(TestDto dto) {

        int radomInt = new Random().nextInt(99999999);
        dto.setTestNo(String.valueOf(radomInt));

        int num = testManageMapper.getTestByNo(dto.getTestNo());
        if(num > 0 ){
            return R.error("已存在编号为"+dto.getTestNo()+"的试验！");
        }

        TestPo po = new TestPo();

        BeanUtils.copyProperties(dto,po);

        String time = String.valueOf(System.currentTimeMillis());

        po.setCreatTimeRub(time);

        int count = testManageMapper.saveTest(po);

        List<DeviceDto> deviceList = dto.getDeviceList();
        List<DevicePo> poList = new ArrayList<>();
        if(deviceList.size() != 0){
            deviceList.stream().forEach(deviceDto -> {
                DevicePo devicePo = new DevicePo();
                BeanUtils.copyProperties(deviceDto,devicePo);
                List<String> electricNo = deviceDto.getElectricNo();
                String join = Joiner.on(",").join(electricNo);
                devicePo.setElectricNo(join);
                devicePo.setTestNo(dto.getTestNo());
                devicePo.setCreateId(dto.getCreatId());
                poList.add(devicePo);
            });

            int insert = testManageMapper.saveDevice(poList);
        }

        return CommonUtils.msg(count);
    }

    @Override
    public Page<AppTestListVo> appTestList(Map<String, Object> params) {
        Query query = new Query(params);
        Page<AppTestListVo> page = new Page<>(query);
        List<AppTestListVo> list =  testManageMapper.appTestList(page, query);
        if(CollectionUtils.isNotEmpty(list)){
            list.stream().forEach(vo -> {
                List<String> devicelist = testManageMapper.getDeviceNoList(vo.getTestNo());
                vo.setDeviceNoList(devicelist);
            });
        }
        return page;
    }

    @Override
    public R getTestList() {
        return CommonUtils.msg(testManageMapper.getTestList());
    }

    @Override
    public R getDeviceList(String no) {
        return CommonUtils.msg(testManageMapper.getDeviceList(no));
    }

    @Override
    public R getPassList(String no) {
        return CommonUtils.msg(testManageMapper.getPassList(no));
    }

    @Override
    public R editTest(TestDto dto) {

        // 修改试验信息
        testManageMapper.updateTest(dto);

        // 删除之前的设备信息
        testManageMapper.deleteDevice(dto.getTestNo());

        List<DeviceDto> deviceList = dto.getDeviceList();
        List<DevicePo> poList = new ArrayList<>();
        deviceList.stream().forEach(deviceDto -> {
            DevicePo devicePo = new DevicePo();
            BeanUtils.copyProperties(deviceDto,devicePo);
            List<String> electricNo = deviceDto.getElectricNo();
            String join = Joiner.on(",").join(electricNo);
            devicePo.setElectricNo(join);
            devicePo.setTestNo(dto.getTestNo());
            devicePo.setCreateId(dto.getCreatId());
            poList.add(devicePo);
        });

        int insert = testManageMapper.saveDevice(poList);

        return CommonUtils.msg(insert);
    }

    @Override
    public R getTestInfo(String testNo) {
        //TestDto vo = new TestDto();
        TestDto vo = testManageMapper.getTestInfo(testNo);
        List<DeviceDto> deviceList = testManageMapper.getDeviceInfo(testNo);
        deviceList.stream().forEach(deviceDto -> {
            String eleNo = testManageMapper.getEleNo(testNo,deviceDto.getDeviceNo(),deviceDto.getPassNo());
            String[] split = eleNo.split(",");
            List<String> list = new ArrayList<>();
            for (int i = 0;i<split.length;i++){
                list.add(split[i]);
            }
            deviceDto.setElectricNo(list);
        });
        vo.setDeviceList(deviceList);
        return CommonUtils.msg(vo);
    }

    @Override
    public R deleteTestInfo(String testNo) {

        testManageMapper.deleteTest(testNo);

        // 删除设备信息
        testManageMapper.deleteDevice(testNo);
        return R.ok("删除成功！");
    }

    @Override
    @Transactional
    public R newCreatTest(TestDto dto) {

        int radomInt = new Random().nextInt(99999999);
        dto.setTestNo(String.valueOf(radomInt));

        int testNum = testManageMapper.getTestByNo(dto.getTestNo());
        if(testNum > 0 ){
            return R.error("已存在编号为"+dto.getTestNo()+"的试验！");
        }

        // TODO: 2023/1/31  记录创建者的基本信息

        TestPo po = new TestPo();

        BeanUtils.copyProperties(dto,po);

        String time = String.valueOf(System.currentTimeMillis());

        po.setCreatTimeRub(time);

        int count = testManageMapper.saveTest(po);

        List<DeviceDto> deviceList = dto.getDeviceList();
        if(deviceList.size() == 0){
            return R.error("后台未获取到设备信息！");
        }
        for(int i = 0;i<deviceList.size();i++){
            // 判断是设备是否在设备登记表里面
            int num = deviceRegisterMapper.getNumByDeviceNo(deviceList.get(i).getDeviceNo());
            if(num != 0){
                return R.error("设备ID不存在，请重新输入或者联系管理员！");
            }
            // 判断设备ID是否在其他实验中使用
            int testNumByDeNo = testManageMapper.getTestByDeviceNo(deviceList.get(i).getDeviceNo());
            if(testNumByDeNo != 0){
                return R.error("该设备仍在其他实验中使用，请确认或联系管理员！");
            }

            // 判断设备是否在线
            int onlineNum = deviceRegisterMapper.judgeIsOnline(deviceList.get(i).getDeviceNo());
            if(onlineNum == 0){
                return R.error("未检测到该设备已经上线，请确认该设备是否正常安装！");
            }
        }
        List<DevicePo> poList = new ArrayList<>();
        deviceList.stream().forEach(deviceDto -> {
            DevicePo devicePo = new DevicePo();
            BeanUtils.copyProperties(deviceDto,devicePo);
            List<String> electricNo = deviceDto.getElectricNo();
            String join = Joiner.on(",").join(electricNo);
            devicePo.setElectricNo(join);
            devicePo.setTestNo(dto.getTestNo());
            devicePo.setCreateId(dto.getCreatId());
            poList.add(devicePo);
        });

        int insert = testManageMapper.saveDevice(poList);

        return CommonUtils.msg(count);
    }
}
